import { createRouter, createWebHashHistory } from "vue-router";
import Home from "../components/Home.vue";
import storage from "../utils/storage";

// 异步路由：动态从后端获取的路由
const routes = [
  {
    path: "/",
    name: "home",
    meta: {
      title: "首页",
    },
    component: Home,
    redirect: "/welcome",
    children: [
      {
        path: "welcome",
        name: "Welcome",

        component: () => import("../views/Welcome.vue"),
      },
      {
        path: "menu",
        name: "Menu",
        meta: {
          title: "菜单管理页",
        },
        component: () => import("../views/Menu.vue"),
      },
      {
        path: "leave",
        name: "Leave",
        meta: {
          title: "休假申请页",
        },
        component: () => import("../views/Leave.vue"),
      },
      {
        path: "approve",
        name: "Approve",
        meta: {
          title: "待审批页",
        },
        component: () => import("../views/Approve.vue"),
      },
    ],
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue"),
  },
  {
    path: "/404",
    name: "404",
    component: () => import("../views/404.vue"),
  },
];
// 异步请求你的地址
// 数据拼接=》异步路由拼接
// 总结：后台管理系统的路由是由
//      固定路由+异步路由 拼接成最终的完整路由

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 例如：如果新增一个路由对象
// router.addRoute("home", {
//   name: "user",
//   path: "/system/user",
//   meta: {
//     title: "用户管理",
//   },
//   component: () => import("../views/User.vue"),
// });

import api from "../api/index";
// 建立异步路由解析规则
const genearateRoute = (menuList) => {
  let arr = [];
  // 要用递归才能拿到二级菜单，并形成一个对象
  const deepList = (list) => {
    while (list.length) {
      let item = list.pop();
      // item一级菜单
      // 一级菜单无action 二级菜单才有
      if (item.action) {
        // 二级
        arr.push({
          name: item.component,
          path: item.path,
          meta: { title: item.menuName },
        });
      }
      if (!item.action && item.children) {
        // 一级 =》再调用去解析children
        deepList(item.children);
      }
    }
  };
  deepList(menuList);
  // arr = [{
  //     name: "user",
  //     path: "/system/user",
  //     meta: {
  //       title: "用户管理",
  //     },
  //   },]
  return arr;
};

//获取异步路由
const asyncLoadRoute = async () => {
  let userInfo = storage.getItem("userInfo") || {};
  if (userInfo.token) {
    //权限菜单最好不要从缓存拿
    let { menuList } = await api.getPermissionList();
    //如何把 menuList =》asyncRoutes？
    let asyncRoutes = genearateRoute(menuList);
    // console.log(asyncLoadRoute, "asyncLoadRoute");
    asyncRoutes.map((route) => {
      const modules = import.meta.glob("../views/*.vue");
      //获取当前路径下的所有vue文件后缀的文件
      // console.log(modules);
      let url = `../views/${route.name}.vue`;
      route.component = modules[url];
      //完成了最后一步
      //循环的方式，把没有异步路由对象addRoute（）放到router规则
      asyncRoutes.forEach((route) => {
        router.addRoute("home", route);
      });
    });

    const routes1 = router.getRoutes();
    // console.log(routes1, "111");
    //routes1这个数组 固定数组 + 异步路由数组 = 完整路由规则
  }
};
asyncLoadRoute();

router.beforeEach(async (to, from, next) => {
  if (to.name) {
    // 固定路由
    // console.log(1);
    // 修改标题
    document.title = to.meta.title;
    next();
  } else {
    // 异步路由
    await asyncLoadRoute();
    let flag = router
      .getRoutes()
      .filter((route) => route.path == to.path).length;
    if (flag) {
      // 说明有路径
      document.title = to.meta.title;
      next(to);
    } else {
      // 说明没有路径
      next("/404");
    }
    // 判断有没有用户访问的是不是规则的路由
    // console.log(2);
  }
});

export default router;
